<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="createItem" v-permission="'adminQuartz.add'">创建</el-button>
    <div class="filter-container">
      <el-input style="width: 300px;" placeholder="输入查询条件按回车" clearable prefix-icon="el-icon-search" class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.queryString"></el-input>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
      </el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:content="v">
        <template v-if="v.key==='enabled'">
          <span v-if="!v.row[v.key]" class="text-label bg-gray">已停用</span>
          <span v-else class="text-label bg-blue">已启用</span>
        </template>
        <template v-else-if="v.key==='last_run_time'">
          <span class="text-bold" :class="v.row.last_run_status=='Y'?'text-green':'text-red'">
            {{v.row[v.key]}}</span>
        </template>
        <template v-else-if="v.key==='running'">
          <span v-if="!v.row[v.key]" class="text-label bg-gray">空闲</span>
          <span v-else class="text-label bg-green">运行中</span>
        </template>
        <span v-else>{{v.row[v.key]}}</span>
      </template>
      <template v-slot:operation="v">
        <el-link type="primary" :disabled="!!v.row.enabled" @click.prevent="editItem(v.row,v.$index)"
          :underline="false">
          <i class="fa fa-pencil" v-permission="'adminQuartz.edit'" title="编辑"></i>
        </el-link>
        <el-link class="ml-5" v-if="!v.row.enabled" type="success" @click.prevent="startOrPauseJob(v.row,1)"
          :underline="false">
          <i class="fa fa-play" v-permission="'adminQuartz.add'" title="启用"></i>
        </el-link>
        <el-link class="ml-5" v-else type="warning" @click.prevent="startOrPauseJob(v.row,0)" :underline="false">
          <i class="fa fa-stop" v-permission="'adminQuartz.delete'" title="停用"></i>
        </el-link>
        <el-link class="ml-5" :disabled="!!v.row.enabled" type="primary" @click.prevent="doOnceJob(v.row)"
          :underline="false">
          <i class="fa fa-repeat" v-permission="'adminQuartz.add'" title="运行一次"></i>
        </el-link>
        <el-link class="ml-5" :disabled="!!v.row.enabled" type="danger" @click.prevent="deleteItem(v.row,v.$index)"
          :underline="false">
          <i class="fa fa-trash" v-permission="'adminQuartz.delete'" title="删除"></i>
        </el-link>
        <el-link class="ml-5" type="info" @click.prevent="showLog(v.row,v.$index)" :underline="false">
          <i class="fa fa-list-ol" title="日志"></i>
        </el-link>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>
    <el-dialog title="日志查看" width="70%" :close-on-click-modal="false" :visible.sync="logDialogShow">
      <el-button style="margin-top:-15px;" class="fr" :disabled="loglist.length==0" type="danger"
        @click.native="emptyLog" :loading="submitLoading">清空
      </el-button>
      <z-table :list="loglist" :tableProps="table2" :columns="table2columns" @editItem="()=>{}" @deleteItem="()=>{}">
      </z-table>
      <z-pagination :pagination="pagination" :total="logtotal" :page.sync="logQuery.page" :limit.sync="logQuery.size"
        @change="getLogList"></z-pagination>
    </el-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'

export default {
  mixins: [commonMixin],
  name: 'adminQuartz',
  components: {},
  data: function () {
    return {
      api: this.$api.quartz,
      apiCreate: this.$api.quartz + 'update',
      name: '任务调度',
      columns: [
        { title: '任务代码', key: 'job_name', width: 100 },
        { title: '任务分组', key: 'job_group', width: 80 },
        { title: '启用状态', key: 'enabled', width: 80 },
        { title: '任务描述', key: 'description', width: 140 },
        { title: '运行状态', key: 'running', width: 80 },
        { title: '上次运行时间', key: 'last_run_time', width: 140 },
        { title: '规则类型', key: 'trigger_type_label', width: 100 },
        { title: 'Cron表达式', key: 'cron', width: 120 },
        { title: '生效起始', key: 'begintime', width: 140 },
        { title: '生效截至', key: 'endtime', width: 140 },
        { title: '计划次数', key: 'runtimes', width: 70 },
        { title: '运行间隔(秒)', key: 'interval_second', width: 90 },
        // { title: '程序集名', key: 'assembly_name', width: 140 },
        { title: '类全名', key: 'class_fullname', width: 170 },
        { title: '备注', key: 'remarks' },
        { title: '修改人', key: 'modify_user', width: 90 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields: [
        {
          title: '任务代码',
          key: 'job_name',
          required: true,
          span: 12,
          props: {
            disabled: false,
          },
        },
        {
          title: '任务分组',
          key: 'job_group',
          required: true,
          span: 12,
          props: {
            disabled: false,
          },
        },
        { title: '规则类型', key: 'trigger_type', required: true, span: 12, name: 'select', options: [] },
        { title: '任务描述', key: 'description', span: 12 },
        // { title: '程序集名', key: 'assembly_name', required: true, span: 12 },
        {
          title: '类全名',
          tips: '自动从后端获取所有的JOB类名，若不确定如何选择请与后端确认',
          key: 'class_fullname',
          required: true,
          span: 24,
          name: 'select',
          options: [],
          props: {
            disabled: false,
          },
        },
        {
          title: '生效起始',
          key: 'begintime',
          span: 12,
          name: 'date',
          props: { type: 'datetime', valueFormat: 'yyyy-MM-dd HH:mm:ss' },
        },
        {
          title: '生效截至',
          key: 'endtime',
          span: 12,
          name: 'date',
          props: { type: 'datetime', valueFormat: 'yyyy-MM-dd HH:mm:ss' },
        },
        { title: '计划次数', key: 'runtimes', name: 'number', span: 12, hidden: false },
        { title: '运行间隔(秒)', key: 'interval_second', name: 'number', span: 12, hidden: false },
        // { title: 'Cron表达式', key: 'cron', hidden: false },
        {
          title: 'Cron表达式',
          key: 'cron',
          name: 'cron',
          hidden: false,
          events: {
            update: (e) => {
              this.data.cron = e
            },
          },
        },
        { title: '备注', key: 'remarks', name: 'textarea' },
      ],
      tableProps: {
        border: true,
        opsColWith: 140,
      },
      typeOptions: [
        { label: 'Cron表达式', value: 'cron' },
        { label: 'Simple规则', value: 'simple' },
      ],
      table2: {
        border: false,
        opsColWith: 80,
        hideOperations: true,
      },
      table2columns: [
        { title: '运行开始时间', key: 'begintime', width: 160 },
        { title: '运行完成时间', key: 'endtime', width: 160 },
        { title: '花费时间(ms)', key: 'spend_time', width: 120 },
        { title: '异常信息', key: 'exception_msg' },
        // { title: '数据1', key: 'data1', width: 100 },
        // { title: '数据2', key: 'data2', width: 100 },
        // { title: '数据3', key: 'data3', width: 100 },
      ],
      initData: { cron: '* * * * * *' },
      logDialogShow: false,
      logQuery: { page: 1, size: 10 },
      loglist: [],
      logtotal: 0,
    }
  },
  methods: {
    formatList(list) {
      let tmp = _.cloneDeep(list)
      return tmp.map((i) => {
        let t = this.typeOptions.find((j) => j.value == i.trigger_type)
        if (t) i.trigger_type_label = t.label
        return i
      })
    },
    formatBeforeSave(data) {
      let tmp = _.cloneDeep(data)
      let arr = data.class_fullname.split('.')
      if (arr.length > 1) {
        arr.pop()
        if (arr[arr.length - 1].toLowerCase() == 'jobs') {
          arr.pop()
        }
        tmp.assembly_name = arr.join('.')
      }
      return tmp
    },
    startOrPauseJob(row, enable) {
      let url = this.api + 'enable'
      this.pageLoading = true
      this.$request(url, { id: row.id, enable }, 'post')
        .then((r) => {
          this.pageLoading = false
          this.$message.success('操作成功')
          this.getList()
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    doOnceJob(row) {
      let url = this.api + 'do'
      this.pageLoading = true
      this.$request(url, { id: row.id }, 'post')
        .then((r) => {
          this.pageLoading = false
          this.$message.success('任务已经开始执行')
          this.getList()
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    showLog(row) {
      this.logQuery = { page: 1, size: 10, jobid: row.id }
      this.loglist = []
      this.logtotal = 0
      this.logDialogShow = true
      this.getLogList()
    },
    getLogList() {
      let url = this.api + 'getloglist'
      this.$request(url, this.logQuery)
        .then((r) => {
          this.loglist = r.list
          this.logtotal = r.total
        })
        .catch(() => {})
    },
    emptyLog() {
      this.$confirm('确认清空此Job的运行日志？').then(() => {
        this.submitLoading = true
        let url = this.api + 'emptylog'
        this.$request(url, { jobid: this.loglist[0].job_id }, 'post')
          .then((r) => {
            this.$message.success('操作成功')
            this.submitLoading = false
            this.logDialogShow = false
          })
          .catch(() => {
            this.submitLoading = false
          })
      })
    },
    getJobClassOptions() {
      let url = this.api + 'getjobclasslist'
      this.$request(url)
        .then((r) => {
          this.getFieldConfig('class_fullname').options = r.map((x) => ({ value: x }))
        })
        .catch(() => {})
    },
  },
  created: function () {
    this.getList()
    this.getFieldConfig('trigger_type').options = this.typeOptions
    this.getJobClassOptions()
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(val, o) {
        this.getFieldConfig('runtimes').hidden = val.trigger_type == 'cron'
        this.getFieldConfig('interval_second').hidden = val.trigger_type == 'cron'
        this.getFieldConfig('cron').hidden = val.trigger_type != 'cron'
        this.getFieldConfig('job_group').props.disabled = !!val.id
        this.getFieldConfig('job_name').props.disabled = !!val.id
        this.getFieldConfig('class_fullname').props.disabled = !!val.id
      },
    },
  },
}
</script>
<style scoped>
</style>
